﻿using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.ExpressApp.Xpo;
using DevExpress.Pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XafDeleteActionByConditionInListView.Module.BusinessObjects;

namespace XafDeleteActionByConditionInListView.Module.Controllers {

  public class TStudentVc : ObjectViewController<ListView, TStudentBo> {
    SimpleAction fBatchCreateAction;
    public TStudentVc() : base() {
      // Target required Views (use the TargetXXX properties) and create their Actions.
      fBatchCreateAction = new SimpleAction(this, "恢复默认数据源", "View");
      fBatchCreateAction.Execute += fBatchCreateAction_Execute;
    }
    private void fBatchCreateAction_Execute(object sender, SimpleActionExecuteEventArgs e) {
      var bItems = ObjectSpace.GetObjects<TStudentBo>();
      ObjectSpace.Delete(bItems);

      string[] bNames = ["张三", "李四", "MyName"];
      foreach (string bName in bNames) {
        TStudentBo bObject = ObjectSpace.FirstOrDefault<TStudentBo>(u => u.Name == bName);
        if (bObject == null) {
          bObject = ObjectSpace.CreateObject<TStudentBo>();
          bObject.Name = bName;
          bObject.Age = 10;
          bObject.Deleted = false;
        }
      }
      ObjectSpace.CommitChanges();
      ObjectSpace.Refresh();

      // 采用这种添加方式，必须执行 ObjectSpace.Refresh(); 执行 View.Refresh(); 是无效的
      //var bNew = ObjectSpace.CreateObject<TStudentBo>();
      //bNew.Name = "ABC";
      //ObjectSpace.CommitChanges();
      //ObjectSpace.Refresh();
    }

    protected override void OnActivated() {
      base.OnActivated();
      // Perform various tasks depending on the target View.
      var bDeleteObjectsVc = Frame.GetController<DeleteObjectsViewController>();
      if (bDeleteObjectsVc != null) {
        bDeleteObjectsVc.Deleting += BDeleteObjectsVc_Deleting;
      }

      View.CollectionSource.Criteria["自定义搜索"] = CriteriaOperator.Parse("[Deleted] == False");
    }

    private void BDeleteObjectsVc_Deleting(object sender, DeletingEventArgs e) {
      // 执行这个，删除操作将无效
      e.Cancel = true;

      foreach (object item in e.Objects) {
        ((TStudentBo)item).Deleted = true;
      }

      ObjectSpace.CommitChanges();
      View.CollectionSource.Reload();

      // 其实不加这句，也能刷新列表，但源码中有这句，原因需要再看。。
      View.Editor.Refresh();
    }

    protected override void OnDeactivated() {
      // Unsubscribe from previously subscribed events and release other references and resources.
      base.OnDeactivated();
    }
    protected override void OnViewControlsCreated() {
      base.OnViewControlsCreated();
      // Access and customize the target View control.
    }
  }
}
